const express = require('express');
const db = require('../db');
const router = express.Router();
 
// 查询用户（支持模糊查询和分页）
router.get('/users', (req, res) => {
    const { user_name, phone, page = 1, pageSize = 10 } = req.query; // 获取查询参数，默认页码为1，每页大小为10
    let sql = 'SELECT * FROM user_info WHERE 1=1'; // 初始化SQL查询
    const params = [];

    // 如果提供了用户名
    if (user_name) {
        sql += ' AND user_name LIKE ?';
        params.push(`%${user_name}%`);
    }

    // 如果提供了手机号
    if (phone) {
        sql += ' AND phone LIKE ?';
        params.push(`%${phone}%`);
    }

    // 分页逻辑：设置 LIMIT 和 OFFSET
    const offset = (page - 1) * pageSize;  // 计算偏移量
    sql += ' LIMIT ? OFFSET ?';
    params.push(parseInt(pageSize, 10), offset); // 添加分页参数

    db.query(sql, params, (err, results) => {
        if (err) return res.status(500).send(err.message);

        // 获取总记录数，计算总页数
        const countSql = 'SELECT COUNT(*) AS total FROM user_info WHERE 1=1' + (user_name || phone ? ' AND ' + (user_name ? 'user_name LIKE ?' : '') + (phone ? 'phone LIKE ?' : '') : '');
        db.query(countSql, params.slice(0, params.length - 2), (err, countResults) => {
            if (err) return res.status(500).send(err.message);
            const total = countResults[0].total; // 总记录数
            const totalPages = Math.ceil(total / pageSize); // 计算总页数
            res.send({
                data: results,          // 当前页的数据
                pagination: {
                    total: total,       // 总记录数
                    totalPages: totalPages, // 总页数
                    page: page,         // 当前页
                    pageSize: pageSize  // 每页大小
                }
            });

        });
     
        });
});

// 添加用户
router.post('/users', (req, res) => {
    const { user_name, phone, password, birthday, sex, position, roles } = req.body;
    const sql = 'INSERT INTO user_info (user_name, phone, password, birthday, sex, position, roles, create_time) VALUES (?, ?, ?, ?, ?, ?, ?, NOW())';
    db.query(sql, [user_name, phone, password, birthday, sex, position, roles], (err, results) => {
        if (err) return res.status(500).send(err.message);
        res.send({ message: '添加成功', userId: results.insertId });
    });
});
 
// 修改用户
router.put('/users/:id', (req, res) => {
    const { id } = req.params;
    const { user_name, phone, password, birthday, sex, position, roles } = req.body;
    const sql = 'UPDATE user_info SET user_name=?, phone=?, password=?, birthday=?, sex=?, position=?, roles=? WHERE user_id=?';
    db.query(sql, [user_name, phone, password, birthday, sex, position, roles, id], (err, results) => {
        if (err) return res.status(500).send(err.message);
        res.send({ message: '修改成功' });
    });
});

// 删除用户
router.delete('/users/:id', (req,  res) => {
    const { id } = req.params;
    const sql = 'DELETE FROM user_info WHERE user_id=?';
    db.query(sql, [id], (err, results) => {
        if (err) return res.status(500).send(err.message);
        res.send({ message: '删除成功' });
    });
});

router.post('/login', async (req, res) => {
    const { username, password } = req.body;
    const query = 'SELECT * FROM user_info WHERE user_name = ? AND password = ?';
    
    db.query(query, [username, password], (error, results) => {
      if (error) throw error;
      if (results.length > 0) {
        res.send({ message: '登录成功', user: results[0] });
      } else {
        res.status(401).send({ message: '用户名或密码错误' });
      }
    });
  });
// 添加用户
router.post('/register', (req, res) => {
    const { user_name, phone, password, birthday, sex, position, roles } = req.body;
    const sql = 'INSERT INTO user_info (user_name, phone, password, create_time) VALUES (  ?, ?, ?, NOW())';
    db.query(sql, [user_name, phone, password, birthday, sex, position, roles], (err, results) => {
        if (err) {
            return res.status(500).send(err.message);
        }
        res.status(201).send({ message: '添加成功', userId: results.insertId });
    });
});
module.exports = router;
